#include "factory.h"



int factory_init(pFactory_t pfac,int threadNum,int queCapacity)
{
    //工厂初始化
    bzero(pfac,sizeof(factory_t));
    pfac->tpThreadNum = threadNum;
    pthread_cond_init(&pfac->cond,NULL);
    pfac->pthid = (pthread_t*)calloc(sizeof(pthread_t),threadNum);//退时free！

    //用户数组
    pfac->users.userNum = 0;
    pfac->maxUsers = MAX_USER;
    pfac->users.userlink = NULL;
    pthread_mutex_init(&pfac->users.mutex,NULL);
    //命令处理相关
    pfac->users.epfd = epoll_create(1);
    ERROR_CHECK(pfac->users.epfd, -1, "epoll_create");
    //队列初始化
    que_init(&pfac->que,queCapacity);

    return 0;
}

//传输任务处理线程
void* worker_fuc(void* p)
{
    pFactory_t pfac = (pFactory_t)p;
    printf("worker %ld :ready\n",pthread_self());    
    ptaskNode_t ptask = NULL;

    while(1)
    {
        pthread_mutex_lock(&pfac->que.queMutex);
        if(!pfac->que.queSize)//队空 睡觉
        {
            printf("worker %ld :task que is empty, sleeping...\n",pthread_self());
            pthread_cond_wait(&pfac->cond,&pfac->que.queMutex);//趁锁 注意这个判断位置的安排，
                                                                //如果先判断队不空的话，就趁不上了
        }
        que_get(&pfac->que,&ptask);
        pthread_mutex_unlock(&pfac->que.queMutex);
        //醒来之后，依据任务的类型，进行文件传输；
        if(ptask->mod)//mod == 1  为从服务器传输文件到客户端
        {
            printf("worker %ld :get task fd:%d call trans_file\n",pthread_self(),ptask->fd);
            trans_file(ptask);
            printf("worker %ld :task fd:%d done.\n",pthread_self(),ptask->fd);
            close(ptask->fd);
            free(ptask);
        }
        else
        {
            printf("worker %ld :get task fd:%d call recv_file\n",pthread_self(),ptask->fd);
            recv_file(ptask);
            printf("worker %ld :task fd:%d done.\n", pthread_self(), ptask->fd);
            close(ptask->fd);
            free(ptask);
        }
        
        
    }
}



int factory_launch(pFactory_t pfac)
{
    int threadNum = pfac->tpThreadNum;
    for(int i = 0;i<threadNum;++i)
    {
        pthread_create(&(pfac->pthid[i]),NULL,worker_fuc,pfac);
    }
    pfac->startFlag = 1;//标识工厂已经启动，防止重复启动
    return 0;
}



int read_config(const char *filename,char args[][20],int argNum)
{
    char buf[20] = {0};
    int argc = 0;
    FILE* config = fopen(filename,"rb");
    if(!config)
    {
        fprintf(stderr,"error in main: config open failed\n");
    }
    while(argc<argNum)
    {
        bzero(&buf,sizeof(buf));
        fgets(buf,20,config);
        if(feof(config))
            break;
        if(buf[0] == '#'||buf[0] == '\n'||buf[0] == 0)
            continue;
        else
        {
            strcpy(args[argc],buf);
            args[argc][strlen(buf)-1] = 0;//删除换行符号
            argc++;
        }
    }
    if(argc == argNum)
        return argc;
    else
    {
        fprintf(stderr,"read_config :wrong num of args\n");
        return -1;
    }
}